<?php
namespace App\Http\Controllers\Api\Card;

use DB;

use Carbon\Carbon;

use Illuminate\Http\Request;

use App\Service\WdhService;

use App\Models\Customer\Customer;  //会员主表

use App\Models\Card\CardCoupon; //卡券表

use App\Models\Card\CardCouponMall; //卡券指定使用门店表

use App\Models\Card\CardCouponCodeGive; //卡券券码赠送记录表

use App\Models\Goods\GoodsSaleEdit; //待发布商品表

use App\Models\Customer\ActivityCodePool; //活动码池子表

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Redis as Redis;

class OutwardCardController extends Controller
{


    /**
     * 券码同步接口
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function codeUpload( Request $request )
    {

        $args_data = json_decode( $request->input('param') ,true );

        //卡券ID
        if ( empty( $args_data['card_id'] ) ) {
            return response()->json(['code' => 100001, 'message' =>'卡券ID不能为空']);
        }

        //券码数组
        if ( empty( $args_data['card_code_list'] ) ) {
            return response()->json(['code' => 100002, 'message' =>'券码序列不能为空']);
        }
        if( !is_array( $args_data['card_code_list'] ) ) {
            return response()->json(['code' => 100003, 'message' =>'券码传参格式有误']);
        }

        //查询卡券信息
        $card_coupon = CardCoupon::find( $args_data['card_id'] );
        if ( !$card_coupon ) {
            return response()->json(['code' => 100004, 'message' =>'卡券信息不存在']);
        }
        if ( $card_coupon['useFlg'] == 0 ) {
            return response()->json(['code' => 100005, 'message' =>'卡券已禁用']);
        }
        if ( $card_coupon['total_num'] <= 0 ) {
            return response()->json(['code' => 100006, 'message' =>'卡券生码数量为0']);
        }
        if ( $card_coupon['total_num'] < count( $args_data['card_code_list'] ) ) {
            return response()->json(['code' => 100007, 'message' =>'卡券生码数量超过限制，生码数量为:'.$card_coupon['total_num']]);
        }

        //检查是否存在领取、使用、作废的券码
        $check_result = ActivityCodePool::select('barcode')->where([['activity_id','=',$args_data['card_id']],['code_status','>',0 ]])->get()->toArray();
        if ( !empty( $check_result ) ) {
            return response()->json(['code' => 100008, 'message' =>'卡券券码已经使用，不可重复上传']);
        }

        $amount = 0; //券金额
        $discount = 0; //券折扣：1~100的整数
        $limit_money = 0; //券使用限额
        $post_id = 0; //商品网购号
        $code_type = 0; //券码类型： 6.现金券 7.折扣券 8.提货券 9.通用券 10.免运费券
        $goods_name = null; //商品名称
        $product_code = null; //商品编码
        $market_price = 0.00; //市场价
        $sale_price = 0.00; //销售价

        /**
         * 券使用类型：0.订单券 1.代金券 2.折扣券 3.提货券 4.通用券 5.免运费券
         */
        if ( $card_coupon['card_type'] == 1) { //代金券
            $code_type = 6;
            $amount = $card_coupon['amount'];
            $limit_money = $card_coupon['limit_money'];
        } elseif ( $card_coupon['card_type'] == 3) { //提货券
            $code_type = 8;
            $post_id = $card_coupon['postID'];
            $sale_price = $card_coupon['salePrice'];

            //查询商品信息
            $goods_sale_edit = GoodsSaleEdit::find( $post_id );
            if ( $goods_sale_edit ) {
                $goods_name = $goods_sale_edit['goodsName'];  //商品名称
                $product_code = $goods_sale_edit['product_code']; //商品编码
                $market_price = $goods_sale_edit['marketPrice']; //市场价
            }
        } elseif ( $card_coupon['card_type'] == 2) { //折扣券
            $code_type = 7;
            $discount = $card_coupon['discount'] * 100;
        } elseif ( $card_coupon['card_type'] == 4) {//通用券
            $code_type = 9;
        } elseif ( $card_coupon['card_type'] == 5) { //免运费券
            $code_type = 10;
            $limit_money = $card_coupon['limit_money'];
        }

        /**
         * 有效期类型：1.静态区间  2.动态时间（天）
         * valid_begin_day 表示自领取后多少天开始生效
         * valid_day 有效期天数
         */
        if ( $card_coupon['time_type'] == 1 ) {
            $code_start_time = $card_coupon['use_start_time'];  //卡券使用起始日期
            $code_end_time = $card_coupon['use_end_time']; //卡券使用结束日期
        } else {
            $code_start_time = date('Y-m-d H:i:s',strtotime('+' . $card_coupon["valid_begin_day"] . ' day'));
            $code_end_time = date('Y-m-d H:i:s',strtotime('+' . $card_coupon["valid_day"] . ' d',strtotime( $code_start_time )));
        }

        /**
         * 发放方式 1、账户券 2、编号券 3、万能券 (发放方式不是账户券时,开始时间和结束时间不受限制)
         */
        if ( $card_coupon['provide_type'] == 1 ) {
            $start_time = $card_coupon['start_time'];  //券发放开始时间
            $end_time = $card_coupon['end_time'];  //券发放结束时间
        } else {
            $start_time = '0000-00-00 00:00:00';
            $end_time   = '0000-00-00 00:00:00';
        }

        //验码方式
        $code_verify_type = $card_coupon['is_mobile_verify'] == 1 ? 1 : 2;

        //卡券索引
        $redis_index = 'COUPONCODE_API_PRECODE_' . $args_data['card_id'];

        Redis::del( $redis_index );

        //利用redis存储和去重券码
        foreach ( $args_data['card_code_list'] as $code ){

            //将码子存进redis里面
            $result = Redis::sAdd( $redis_index , $code );

            //码子重复
            if( $result == 0 ){
                continue;
            }
        }

        //获取码子信息
        $code_pool = Redis::sMembers( $redis_index );

        try {

            //开启事务
            DB::beginTransaction();

            $insertSQL = 'REPLACE INTO activity_code_pool (uuid,timeStamp,creator,createTime,barcode,code_type,activity_id,activity_uuid,external_code,activity_name,activity_start_time,activity_end_time,code_start_time,code_end_time,code_verify_type,postID,goods_name,product_code,market_price,sale_price,code_amount,code_limit_amount,code_discount,code_use_type) VALUES ';

            foreach ( $code_pool as &$barcode ) {

                $insertSQL .=  "('" . makeUuid() . "', '" . Carbon::now() . "' , 'api', '" . Carbon::now() . "', '" . $barcode . "',"  . $code_type . ","  .
                    $card_coupon['card_id'] . ", '" . $card_coupon['uuid'] .  "' , '" . $card_coupon['external_no'] . "', '" . $card_coupon['card_name'] . "', '" . $start_time . "', '" . $end_time .  "', '" . $code_start_time . "', '" . $code_end_time . "'," . $code_verify_type . "," . $post_id . ", '" . $goods_name .
                    "', '" . $product_code . "','" . $market_price . "'," . $sale_price . "," . $amount . "," . $limit_money . "," . $discount . "," . $card_coupon['card_type'] ."),";
            }

            //插入活动码数据
            DB::statement( rtrim( $insertSQL,',') );

            //更新生码状态 0、未生码 1、已生码 2、正在生码
            $card_coupon_update = CardCoupon::where(['card_id'=>$card_coupon['card_id']])->update(['create_code_stat'=>1]);
            if ( $card_coupon_update == 0 ) {
                return response()->json(['code' => 100009 , 'message' => '更新生码状态失败' ]);
            }

            DB::commit();

        } catch (\Exception $e) {

            DB::rollBack();

            return response()->json(['code' => 100010 , 'message' => '卡券同步有误' ]);
        }

        return response()->json(['code' => 200, 'message' => 'ok']);

    }


    /**
     * 券码批量发放接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchGrant( Request $request )
    {

        $args_data = json_decode( $request->input('param') ,true );

        if ( empty( $args_data['card_id'] ) ) {
            return response()->json(['code' => 100001, 'message' =>'卡券ID不能为空']);
        }

        //会员类型  1.会员名 2.卡号
        if ( empty( $args_data['cust_type'] ) ) {
            return response()->json(['code' => 100002, 'message' =>'会员类型不能为空']);
        }

        //会员数组
        if ( empty( $args_data['cust_list'] ) ) {
            return response()->json(['code' => 100003, 'message' =>'会员序列不能为空']);
        }
        if( !is_array( $args_data['cust_list'] ) ) {
            return response()->json(['code' => 100004, 'message' =>'会员序列传参格式有误']);
        }

        //查询卡券信息
        $card_coupon = CardCoupon::find( $args_data['card_id'] );
        if ( !$card_coupon ) {
            return response()->json(['code' => 100005, 'message' =>'卡券信息不存在']);
        }

        $switch= 2;  //从已生成的码中分配
        if ( in_array( $card_coupon['card_type'],array(1,2,5)) && in_array( $card_coupon['provide_type'], array(1, 3))) { //发放方式为账户券的代金券、折扣券及免运券或者方法方式为万能券
            $switch = 1;  //生成券码并分配
        }

        $cust_data = []; //返回会员数据数组
        foreach ( $args_data['cust_list'] as $k=>$custID ) {
            $cust_data[] = $custID;
        }

        $args_array = [
            'card_id' => $args_data['card_id'], //卡券ID
            'cust_data' => $cust_data,
            'type' => $args_data['cust_type'],
            'switch' => $switch //券码分配来源
        ];

        //发放券码脚本
        $card_handle = WdhService::codeHandle( $args_array );
        if ( $card_handle['code'] != 200 ) {
            return response()->json(['code' => $card_handle['code'], 'message' =>$card_handle['message']]);
        }

        return response()->json(['code' => 200, 'message' =>'券发放成功']);

    }


    /**
     * 卡券信息查询接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function get( Request $request )
    {

        $args_data = json_decode( $request->input('param') ,true );

        //卡券类型 1.代金券 2.折扣券 3.提货券 4.通用券 5.免运费券
        if ( empty( $args_data['card_type'] ) ) {
            return response()->json(['code' => 100001, 'message' =>'卡券类型不能为空']);
        }
        if ( empty( $args_data['limit'] ) ) { //每页显示条数,不传默认为10
            $args_data['limit'] = 10;
        }
        if ( empty( $args_data['page'] ) ) { //页码,不传默认为1
            $args_data['page'] = 1;
        }

        $where = [];
        $where[] = ['card_type',$args_data['card_type']];

        if ( isset( $args_data['card_id'] ) && !empty( $args_data['card_id'] ) ) { //如果存在卡券ID,则查询对应的卡券信息
            $where[] = ['card_id',$args_data['card_id']];
        }
        if ( isset( $args_data['card_name'] ) && !empty( $args_data['card_name'] ) ) { //如果存在卡券名称,则查询对应的卡券信息
            $where[] = ['card_name',$args_data['card_name']];
        }

        //查询卡券信息
        $card_coupon = CardCoupon::where($where)->orderBy('createTime', 'DESC')->paginate( $args_data['limit'] )->toArray();

        $card_mall = [];  //部分门店数组
        $card_merchant = [];  //部分商户数组
        $card_array = []; //卡券信息返回数组

        if ( $card_coupon['data'] ) {

            foreach ( $card_coupon['data'] as &$card ) {

                //门店支持类型为部分门店时 1.全部门店 2.部分门店
                if ( $card['mall_support_type'] == 2 ) {

                    //查询门店ID,门店名称
                    $card_mall = CardCouponMall::select('relation_id as mall_id','relation_name as mall_name')
                                 ->where(['card_id'=> $card['card_id'],'relation_type'=>1 ])->get()->toArray();
                }

                //商户支持类型为部分商户时 1.全部商户 2.部分商户
                if ( $card['merchant_support_type'] == 2 ) {

                    //查询商户ID,商户名称
                    $card_merchant = CardCouponMall::select('relation_id as merchant_id','relation_name as merchant_name')
                                     ->where(['card_id'=> $args_data['card_id'],'relation_type'=>2 ])->get()->toArray();
                }

                $card_array[] = [
                    'card_name' => app_to_string( $card['card_name'] ),
                    'card_pic' => app_to_string( $card['card_pic'] ),
                    'card_type' => app_to_int( $card['card_type'] ),
                    'grant_type' => app_to_int( $card['provide_type'] ),
                    'start_time' => app_to_string( $card['start_time'] ),
                    'end_time' => app_to_string( $card['end_time'] ),
                    'time_type' => app_to_int( $card['time_type'] ),
                    'valid_day' => app_to_int( $card['valid_day'] ),
                    'valid_begin_day' => app_to_int( $card['valid_begin_day'] ),
                    'grant_total' => app_to_int( $card['total_num'] ),
                    'discount' => app_to_decimal( $card['discount'] ),
                    'amount' => app_to_decimal( $card['amount'] ),
                    'limit_money' => app_to_decimal( $card['limit_money'] ),
                    'get_num' => app_to_int( $card['getNum'] ),
                    'use_num' => app_to_int( $card['useNum'] ),
                    'post_id' => app_to_string( $card['postID'] ),
                    'sale_price' => app_to_decimal( $card['salePrice'] ),
                    'card_description' => app_to_string( $card['description'] ),
                    'repeat_count' => app_to_int( $card['repeat_count'] ),
                    'mall_support_type' => app_to_int( $card['mall_support_type'] ),
                    'mall' => $card_mall, //部分门店数组
                    'merchant_support_type' => app_to_int( $card['merchant_support_type'] ),
                    'merchant' => $card_merchant, //部分商户数组
                    'can_give_friend' => app_to_int( $card['can_give_friend'] ),
                    'support_condition' => app_to_int( $card['support_condition'] ),
                    'get_way' => app_to_int( $card['get_way'] ),
                    'points_price' => app_to_decimal( $card['pointsPrice'] ),
                    'money_price' => app_to_decimal( $card['moneyPrice'] ),
                ];

            }
        }

        $data = [
            'total' => $card_coupon['total'] ? $card_coupon['total'] : 0,
            'list' => $card_array
        ];

        return response()->json(['code' => 200, 'message' =>'ok', 'data'=> $data]);

    }


    /**
     * 会员卡券列表查询接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getList( Request $request )
    {

        $args_data = json_decode( $request->input('param') ,true );

        //会员名
        if ( empty( $args_data['cust_id'] ) ) {
            return response()->json(['code' => 100001, 'message' =>'会员名不能为空']);
        }
        if ( empty( $args_data['limit'] ) ) { //每页显示条数,不传默认为10
            $args_data['limit'] = 10;
        }
        if ( empty( $args_data['page'] ) ) { //页码,不传默认为1
            $args_data['page'] = 1;
        }

        //查询会员信息
        $customer = Customer::select('pcustID')->where(['custID'=>$args_data['cust_id']])->first();
        if ( !$customer ) {
            return response()->json(['code' => 100002, 'message' => '会员不存在']);
        }

        $where = [];
        $where[] = ['pcustID','=',$customer['pcustID']]; //会员号
        $where[] = ['code_type','>',5]; //券码类型：6.现金券 7.折扣券 8.提货券 9.通用券 10.免运费券

        if ( isset( $args_data['card_status'] ) && !empty( $args_data['card_status'] ) ) { //卡券使用状态 1.未使用 2.已使用 3.已过期 (不传则查询全部)

            if ( $args_data['card_status'] == 1 ) {  //查询已领取未使用且未过期券码

                $where[] = ['card_status','=',1];
                $where[] = ['code_end_time','>=',Carbon::now()];

            } else if( $args_data['card_status'] == 2 ) { //查询已使用的券码

                $where[] = ['card_status','=',2];

            } else { //查询已过期券码

                $where[] = ['card_status','=',1];
                $where[] = ['code_end_time','<',Carbon::now()];
            }
        }

        //查询活动码信息
        $code_pool = ActivityCodePool::where($where)->orderBy('get_time', 'DESC')->paginate( $args_data['limit'] )->toArray();

        $card_array = []; //返回卡券列表数组
        $give = 0; //卡券是否可转赠 0、不可赠送 1、可转赠一次 ,2、可转赠多次

        if ( $code_pool['data'] ) {

            foreach ( $code_pool['data'] as &$card ) {

                //如果是提货券的时候标题显示商品名称( 默认为活动名称)
                $goods_name = $card['activity_name'];

                if ( $card['code_type'] == 8 &&  !empty( $card['postID'] ) ) { //提货券

                    $goods_sale_edit = GoodsSaleEdit::find( $card['postID'] );
                    if ( $goods_sale_edit ) {
                        $goods_name = $goods_sale_edit['goodsName']; //商品名称
                    }
                }

                //查询卡券卡券是否可转赠：0、不可赠送 1、可转赠一次 ,2、可转赠多次
                $card_coupon = CardCoupon::select('privilege_description','can_give_friend')->find( $card['activity_id'] );

                if ( $card_coupon ) {

                    if ( $card_coupon['can_give_friend'] == 1 ) { //可以转赠一次

                        $give = 2 ; //可以转赠

                        //查询卡券转赠记录
                        $code_give = CardCouponCodeGive::select('id')->where(['barcode'=>$card['barcode']])->get()->toArray();
                        if ( $code_give ) { //存在转赠记录,则为朋友赠送
                            $give = 1 ;
                        }
                    } else if ( $card_coupon['can_give_friend'] == 2 ) {  //可以转赠多次
                        $give = 2  ;
                    }
                }

                $card_array[] = [
                    'barcode' => app_to_string( $card['barcode'] ),
                    'code_use_type' => app_to_int( $card['code_use_type'] ),
                    'activity_name' => app_to_string( $card['activity_name'] ),
                    'product_name' => app_to_string ( $goods_name ), //商品名称
                    'give' => $give, //0.不可转赠，1.朋友赠送，2.可转赠
                    'card_amount' => app_to_decimal( $card['code_amount'] ),
                    'card_limit_amount' => app_to_decimal( $card['code_limit_amount'] ),
                    'card_discount' => app_to_int( $card['code_discount'] )/100,
                    'sale_price' => app_to_decimal( $card['sale_price'] ),
                    'market_price' => app_to_decimal( $card['market_price'] ),
                    'privilege_description' => isset( $card_coupon['privilege_description'] ) ? app_to_string( $card_coupon['privilege_description'] ) : '',//优惠说明
                    'code_start_time' => app_to_string( date('Y-m-d H:i:s',strtotime( $card['code_start_time'] ) ) ),//活动码使用开始时间
                    'code_end_time' => app_to_string( date('Y-m-d H:i:s',strtotime( $card['code_end_time'] ) ) )//活动码使用结束时间
                ];
            }
        }

        $data = [
            'total' => $code_pool['total'] ? $code_pool['total'] : 0,
            'list' => $card_array
        ];

        return response()->json(['code' => 200, 'message' =>'ok', 'data'=> $data]);

    }

}